package com.tungse.study.file;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * @author Tungse
 */
public class ServerReaderThread extends Thread{

    private Socket socket;
    public ServerReaderThread(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            //1 得到客户端的socket 流
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            //2 读取客户端发送的文件类型
            String fileSuffix = dis.readUTF();
            System.out.println("客户端发送的文件类型是：" + fileSuffix);
            //3 定义文件的输出信息
            FileOutputStream fos = new FileOutputStream("D:\\" + System.currentTimeMillis() + fileSuffix);
            //4 读取客户端发送过来的文件数据
            int len;
            byte[] buffer = new byte[1024];
            while ((len = dis.read(buffer)) != -1) {
                System.out.println("读取了" + len + "个字节");
                //5 写入文件内容
                fos.write(buffer, 0, len);
            }
            fos.close();
            System.out.println("文件接收完毕");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
